import Vue from 'vue'
import App from './App'
import http from './libs/request.js';
import store from './store'
import graceChecker from '@/js_sdk/graceui-dataChecker/graceChecker.js';

import uView from './uview-ui/index.js';
Vue.use(uView);

Vue.prototype.$store = store
Vue.prototype.graceChecker = graceChecker;

Vue.prototype.$http = http

//节流throttle代码
Vue.prototype.throttle = function (fn,wait){
    var pre = Date.now();
    return function(){
        var context = this;
        var args = arguments;
        var now = Date.now();
        if( now - pre >= wait){
            fn.apply(context,args);
            pre = Date.now();
        }
    }
}
/**
 * 获取页面参数
 * */
Vue.prototype.getPageOptions = function(){
    let pages = getCurrentPages();

    let options = pages[pages.length-1].options;
    return options
}
/**
 * 展示提示信息
 * @param {String}		msg			提示信息
 * @param {Function}	after		提示后的回调	  
 * @param {Int} 		duration 	提示持续时间 & 等待执行回调的前置时间  不传默认1000
 * */
Vue.prototype.showToast = function(msg, after, duration) {
	if (!duration) duration = 1000;
	uni.showToast({
		title: msg,
		icon: 'none',
		duration,
	});
	if (after) {
		setTimeout(after, duration);
	}
}

Vue.prototype.shortStr = (str, length) => {
	if (str.length <= length)	return str;
	return str.substring(0, length - 1) + '...';
}

Vue.config.productionTip = false

// 构造EventBus
function EventBusClass() {
    this.msgQueues = {}
}

EventBusClass.prototype = {
    // 将消息保存到当前的消息队列中
    on: function(msgName, func) {
        if (this.msgQueues.hasOwnProperty(msgName)) {
            if (typeof this.msgQueues[msgName] === 'function') {
                this.msgQueues[msgName] = [this.msgQueues[msgName], func]                
            } else {
                this.msgQueues[msgName] = [...this.msgQueues[msgName], func]    
            }
        } else {
            this.msgQueues[msgName] = func;
        }
    },
    // 消息队列中仅保存一个消息
    one: function(msgName, func) {
        // 无需检查msgName是否存在
        this.msgQueues[msgName] = func;
    },
    // 发送消息
    emit: function(msgName, msg) {
        if (!this.msgQueues.hasOwnProperty(msgName)) {
            return
        }
        if (typeof this.msgQueues[msgName] === 'function') {
            this.msgQueues[msgName](msg)
        } else {
            this.msgQueues[msgName].map((fn) => {
                fn(msg)
            })
        }
    },
    // 移除消息
    off: function(msgName) {
        if (!this.msgQueues.hasOwnProperty(msgName)) {
            return
        }
        delete this.msgQueues[msgName]
    }
}

// 将EventBus放到window对象中
const EventBus = new EventBusClass()
Vue.prototype.EventBus = EventBus

App.mpType = 'app'
const app = new Vue({
    ...App,
	store
})
app.$mount()
